package com.ruoyi.web.controller.minio.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.modules.domain.Credit;
import com.ruoyi.modules.service.CreditService;
import com.ruoyi.web.controller.minio.config.MinioConfig;
import com.ruoyi.web.controller.minio.service.MinioService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 分布式文件存储 minio
 */
@RequestMapping("/minio")
@RestController
public class MinioController {

    @Autowired
    private DocumentConverter converter;

    @Autowired
    private CreditService creditService;

    @Autowired
    private MinioService minioService;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * minio上传
     * @param file 文件
     * @param bucketName 桶名
     * @param creditId 贷款编号
     * @return
     */
    @PostMapping("/uploadReceipt")
    public AjaxResult uploadReceipt(@RequestParam("file") MultipartFile file, @RequestParam("bucketName")  String bucketName, @RequestParam("creditId") Long creditId) {
        try {
            System.out.println(creditId);
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            if (!minioService.bucketExists(bucketName)) {
                minioService.makeBucket(bucketName);
            }
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的文件名" + objectName);

            InputStream inputStream = file.getInputStream();
            minioService.putObject(bucketName, objectName, inputStream);
            inputStream.close();

            Credit credit = creditService.selectCreditById(creditId);

            // multipartFile转java.io.File
            File toFile = null;
            if(file.equals("")||file.getSize()<=0){
                file = null;
            }else {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }

            System.out.println(toFile);

            // 文件转化
            converter.convert(toFile).to(new File("E:/个人受理证明.pdf")).execute();
            System.out.println("word文件转换成pdf文件成功!");

            // 程序结束时删除临时文件
            deleteFile(toFile);

            String filePath = "E:/个人受理证明.pdf";
            // 将java.io.File转为MultipartFile
            File newFile = new File(filePath);
            FileInputStream newInputStream = new FileInputStream(newFile);
            MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "text/plain", IOUtils.toByteArray(newInputStream));

            System.out.println(multipartFile);

            String uploadReceiptWordPath = FileUploadUtils.upload(RuoYiConfig.getUploadReceiptWord(), multipartFile);

            System.out.println("上传成功后的url: " + uploadReceiptWordPath);

            if (creditService.updateUploadReceiptWord(creditId, uploadReceiptWordPath)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("uploadReceiptWordPath", uploadReceiptWordPath);
                ajax.put("message", "上传成功");
                ajax.put("fileName", file.getOriginalFilename());
                credit.setUploadReceiptWord(uploadReceiptWordPath);
                creditService.updateCredit(credit);
                return ajax;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("上传失败");
    }

    /**
     * InputStream 转 File
     * @param ins
     * @param file 文件
     */
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 删除临时文件
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();

            }

        }
    }
}
